<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="事件名称" prop="eventTitle">
        <el-select v-model="queryParams.eventTitle" placeholder="请选择查评事件" clearable filterable>
          <!-- 使用 v-for 循环渲染选项 -->
          <el-option v-for="option in reviewEventsOptions" :key="option" :label="option" :value="option"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="评审类型" prop="reviewClassify">
        <el-input v-model="queryParams.reviewClassify" placeholder="请输入评审类型" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="评审人" prop="member">
        <el-input v-model="queryParams.member" placeholder="请输入评审人" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="创建人" prop="createBy">
        <el-input v-model="queryParams.createBy" placeholder="请输入创建人" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="创建时间">
        <el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
          range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置
        </el-button>
<!--        <el-button icon="el-icon-refresh" size="mini" @click="exportTheReport">应急能力报告导出-->
<!--        </el-button>-->
        <!--        <el-button icon="el-icon-refresh" size="mini" @click="ExportTheReport"-->
        <!--        >导出报告测试-->
        <!--        </el-button-->
        <!--        >-->
      </el-form-item>

    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="eventList" @selection-change="handleSelectionChange"
      @row-click="handleRowClick" ref="table" border>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="50" align="center" header-align="left" />
      <el-table-column label="事件名称" min-width="260" align="left" prop="eventTitle" :show-overflow-tooltip="true" sortable />
      <el-table-column label="评审类型" min-width="150" align="center" prop="reviewClassify" />
      <el-table-column label="状态" align="center" min-width="80" prop="state">
        <template slot-scope="scope">
          <el-tag :type="getTagType(scope.row.state)">{{ scope.row.state }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" min-width="80" prop="createBy" />
      <el-table-column label="创建日期" align="center" prop="createTime" min-width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d} {hh}:{ss}:{mm}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-download" @click="exportOut(scope.row , '1')"
            v-hasPermi="['system:manger:inspectionReport']">导出报告</el-button>
<!--          <el-button size="mini" type="text" icon="el-icon-download" @click="exportOut(scope.row, '2')"-->
<!--            v-hasPermi="['system:manger:preview']">个人报告-->
<!--          </el-button>-->
<!--          <el-button size="mini" type="text" icon="el-icon-download" @click="exportTheReport(scope.row)"-->
<!--                     v-hasPermi="['system:manger:preview']">总报告导出-->
<!--          </el-button>-->
          <div id="bodyContainer"></div>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
  </div>
</template>
<script>
  import {
    listManger,
    getManger,
    delManger,
    addManger,
    updateManger,
  } from "@/api/system/manger";
  import PeopleSelect from "../../../components/Selection/index.vue"
  import DepartmentDialog from "../../../components/DepartmentDialog/index.vue"
  import {
    inspectionReport,
    listEvent,
    listEventReview
  } from "@/api/system/review/event";
  import {
    exportTheReports,
    getReviewEvents
  } from "@/api/system/review/groping";
  export default {
    name: "Manger",
    dicts: ["sys_normal_disable"],
    components: {
      PeopleSelect,
      DepartmentDialog,
    },
    data() {
      return {
        // 按钮loading
        // buttonLoading: false,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 表格数据
        eventList: [],
        dateRange: [],
        // 弹出层标题
        title: "",
        pdfUrl: "",
        // 是否显示弹出层
        open: false,
        docxOptions: {
          className: "kaimo-docx-666", // string：默认和文档样式类的类名/前缀
          inWrapper: true, // boolean：启用围绕文档内容的包装器渲染
          ignoreWidth: false, // boolean：禁用页面的渲染宽度
          ignoreHeight: false, // boolean：禁止渲染页面高度
          ignoreFonts: false, // boolean：禁用字体渲染
          breakPages: true, // boolean：在分页符上启用分页
          ignoreLastRenderedPageBreak: true, // boolean：在 lastRenderedPageBreak 元素上禁用分页
          experimental: false, // boolean：启用实验功能（制表符停止计算）
          trimXmlDeclaration: true, // boolean：如果为true，解析前会从​​ xml 文档中移除 xml 声明
          useBase64URL: false, // boolean：如果为true，图片、字体等会转为base 64 URL，否则使用URL.createObjectURL
          useMathMLPolyfill: false, // boolean：包括用于 chrome、edge 等的 MathML polyfill。
          showChanges: false, // boolean：启用文档更改的实验性渲染（插入/删除）
          debug: false, // boolean：启用额外的日志记录
        },
        reviewEventsOptions: [], //  用于存储后台返回的查评事件选项
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          reviewUnit: undefined,
          eventTitle: undefined,
          member: undefined,
          reviewClassify: undefined,
          startTime: undefined,
          endTime: undefined,
          reviewContentSet: undefined,
          reviewMode: undefined,
          reviewEventShows: undefined,
          validStatus: '有效',

        },
        // 表单参数
        form: {},
        selectedRows: [],
        Showbox: false,
      };
    },
    created() {
      this.getList();
      this.queryParams.member = this.$store.state.user.nikename;
      // 在组件加载后，请求后台接口获取下拉框数据
      this.fetchReviewEventsData();
    },
    methods: {
      open1() {
        this.peopleOpen = true;
      },
      open2() {
        this.peopleOpen1 = true;
      },
      //选择人的确定按钮事件 submitPeople(nikeNamelist)方法传参一个默认接收用户昵称数组   submitPeople(peopleList,nikeNamelist)方法传参两个则是接收用户昵称数组和用户账号数组
      submitPeople(peopleList) {
        this.peopleOpen = false;
      },
      submitPeople1(peopleList) {
        this.peopleOpen1 = false;
      },
      handleRowClick(row) {
        this.$refs.table.toggleRowSelection(row);
      },
      handleShow() {
        this.Showbox = !this.Showbox
        const element = this.$refs.handle_box_content;
        if (this.Showbox) {
          element.style.overflow = 'visible';
          element.style.height = 'fit-content'
        } else {
          element.style.overflow = 'hidden';
          element.style.height = '50px'
        }
      },
      // 请求后台接口获取查评事件数据
      fetchReviewEventsData() {
        getReviewEvents().then(response => {
          response.data.forEach(item => {
            this.reviewEventsOptions.push(item.review_events);
          })
        }).finally(() => {});
      },
      /** 查询列表 */
      getList() {
        this.loading = true;
        listEventReview(this.addDateRange(this.queryParams, this.dateRange)).then((response) => {
          this.eventList = response.data;
          this.total = response.dataCount;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          ID: undefined,
          refId: undefined,
          projectId: undefined,
          projectName: undefined,
          SORT: undefined,
          batchCode: undefined,
          toolName: undefined,
          kindNumber: undefined,
          TYPE: undefined,
          FACTORY: undefined,
          custodyPerson: undefined,
          startTime: undefined,
          endTime: undefined,
          managePerson: undefined,
          RESULTS: undefined,
          inspectDate: undefined,
          nextInspectDate: undefined,
          REMARK: undefined,
          FILE: undefined,
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.queryParams.reviewUnit = '';
        this.queryParams.reviewClassify = '';
        this.queryParams.createBy = '';
        this.queryParams.eventTitle = '';
        this.dateRange = [];
        this.handleQuery();
      },
      /** 导出报告测试按钮操作 */
      exportTheReport(rows) {
        this.$modal.loading("导出中")
        let data = {
          userName: this.queryParams.member,
          id: rows.id,
          event: rows.reviewClassify+'总报告'
        }
        const row = rows;
        exportTheReports(data).then((response) => {
          console.log(response)
          let dataName = "";
          if (response == '') {
            this.$modal.closeLoading();
          } else {
            this.$modal.closeLoading();
            let data = new Blob([response], {
              type: 'application/msword;charset=utf-8'
            });
            if (typeof window.chrome !== 'undefined') {
              // chrome
              const link = document.createElement('a');
              link.href = window.URL.createObjectURL(data);
              if (event == "2") {
                link.download = row.eventTitle + this.queryParams.member;
              } else {
                link.download = row.eventTitle;
              }
              link.click();
            } else if (typeof window.navigator.msSaveBlob !== 'undefined') {
              // IE
              const blob = new Blob([data], {
                type: 'application/force-download'
              });

              if (event == "2") {
                dataName = row.eventTitle + this.queryParams.member;
              } else {
                dataName = row.eventTitle;
              }
              window.navigator.msSaveBlob(blob, dataName);
            } else {
              if (event == "2") {
                dataName = row.eventTitle + this.queryParams.member;
              } else {
                dataName = row.eventTitle;
              }
              // Firefox
              const file = new File([data], dataName, {
                type: 'application/force-download'
              });
              window.open(URL.createObjectURL(file));
            }
          }

        });
        // 在这里编写重置报告的逻辑
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map((item) => item.id);
        this.single = selection.length !== 1;
        this.selectedRows = selection;
        this.multiple = !selection.length;
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.$router.push({
          path: "/Admission/formDialog",
          // query: {title:"" },
        });
      },
      /** 导出按钮操作 */
      exportOut(row, event) {
        if (row.state == '未评审') {
          return this.$message.warning("该数据还未进行评审!");
        }
        if (event == '2' && this.queryParams.member == '') {
          return this.$message.warning("请输入评审人!");
        }
        this.$modal.loading("导出中")
        this.reset();
        const ID = row.id || this.ids;
        let data = {
          userName: this.queryParams.member,
          id: ID,
          event: event,
          type : row.reviewClassify
        }
        inspectionReport(data).then((response) => {
          let dataName = "";
          if (response == '') {
            this.$modal.closeLoading();
          } else {
            this.$modal.closeLoading();
            let data = new Blob([response], {
              type: 'application/msword;charset=utf-8'
            });
            if (typeof window.chrome !== 'undefined') {
              // chrome
              const link = document.createElement('a');
              link.href = window.URL.createObjectURL(data);
              if (event == "2") {
                link.download = row.eventTitle + this.queryParams.member;
              } else {
                link.download = row.eventTitle;
              }
              link.click();
            } else if (typeof window.navigator.msSaveBlob !== 'undefined') {
              // IE
              const blob = new Blob([data], {
                type: 'application/force-download'
              });

              if (event == "2") {
                dataName = row.eventTitle + this.queryParams.member;
              } else {
                dataName = row.eventTitle;
              }
              window.navigator.msSaveBlob(blob, dataName);
            } else {
              if (event == "2") {
                dataName = row.eventTitle + this.queryParams.member;
              } else {
                dataName = row.eventTitle;
              }
              // Firefox
              const file = new File([data], dataName, {
                type: 'application/force-download'
              });
              window.open(URL.createObjectURL(file));
            }
          }

        });
      },
      getTagType(state) {
        if (state === '已评审') {
          return 'success'; // 返回成功类型的标签
        } else if (state === '未评审') {
          return 'danger'; // 返回失败类型的标签
        } else if (state === '部分未评审') {
          return 'warning'; // 其他情况为空类型的标签
        } else {
          return '';
        }
      },
      getTagText(state) {
        if (state === '已评审') {
          return '已评审';
        } else if (state === '未评审') {
          return '未评审';
        } else if (state === '部分未评审') {
          return '部分未评审';
        } else {
          return '';
        }
      },
      /** 预览按钮操作 */
      preview(row) {
        this.loading = true;
        this.reset();
        const ID = row.id || this.ids;
        inspectionReport(ID).then((response) => {
          if (response == '') {
            this.loading = false;
          } else {
            this.loading = false;
            let data = new Blob([response], {
              type: 'application/msword,charset=utf-8'
            });
            // 将file转为buffer
            let fr = new FileReader();
            fr.readAsArrayBuffer(data);
            fr.addEventListener("loadend", (e) => {
              let buffer = e.target.result;
              this.docxRender(buffer);
            }, false);
          }
        });
      },
      // 渲染docx
      docxRender(buffer) {
        let bodyContainer = document.getElementById("bodyContainer");
        renderAsync(
          buffer, // Blob | ArrayBuffer | Uint8Array, 可以是 JSZip.loadAsync 支持的任何类型
          bodyContainer, // HTMLElement 渲染文档内容的元素,
          null, // HTMLElement, 用于呈现文档样式、数字、字体的元素。如果为 null，则将使用 bodyContainer。
          this.docxOptions // 配置
        ).then(res => {})
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate((valid) => {
          if (valid) {
            // this.buttonLoading = true;
            if (this.form.ID != null) {
              updateManger(this.form)
                .then((response) => {
                  this.$modal.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                })
                .finally(() => {
                  // this.buttonLoading = false;
                });
            } else {
              addManger(this.form)
                .then((response) => {
                  this.$modal.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                })
                .finally(() => {
                  // this.buttonLoading = false;
                });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const IDs = row.id || this.ids;
        this.$modal
          .confirm('是否确认删除工器具管理编号为"' + IDs + '"的数据项？')
          .then(() => {
            this.loading = true;
            return delManger(IDs);
          })
          .then(() => {
            this.loading = false;
            this.getList();
            this.$modal.msgSuccess("删除成功");
          })
          .catch(() => {})
          .finally(() => {
            this.loading = false;
          });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download(
          "system/manger/export", {
            ...this.queryParams,
          },
          `manger_${new Date().getTime()}.xlsx`
        );
      },
    },
  };
</script>
<style>
  .handle_box_content {
    width: 81%;
    height: 50px;
    overflow: hidden;
  }

  .el-forms {
    display: flex;
    flex-wrap: nowrap;
    justify-content: space-between;
  }
</style>
